package com.yun.zf.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.admin.mapper.ZfHousePictureMapper;
import com.yun.zf.admin.service.ZfHousePictureService;
import com.yun.zf.admin.service.ZfHouseScoreService;
import com.yun.zf.common.admin.dto.house.AdminHousePicDto;
import com.yun.zf.common.app.domain.ZfHousePicture;
import com.yun.zf.common.app.domain.ZfHouseScore;
import com.yun.zf.common.constant.Constants;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.utils.AliyunOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 房源图片表 服务实现类
 * </p>
 *
 * @author cj
 * @since 2021-01-29
 */
@Service
@Slf4j
public class ZfHousePictureServiceImpl extends ServiceImpl<ZfHousePictureMapper, ZfHousePicture> implements ZfHousePictureService {
    @Autowired
    private AliyunOssUtil ossUtil;
    @Autowired
    private ZfHouseScoreService scoreService;
    @Override
    public Response uploadHousepic(MultipartFile[] files, HttpServletRequest request, Long provCode, Long cityCode) {
        try {
            List<Map<String,String>> pictureList = new ArrayList<>();
            // 1 图片上传
            if (files != null && files.length > 0) {
                // 如果是封面图先查询封面是否已经存在
                int type =Integer.parseInt(request.getParameter("type"));
                for (MultipartFile file : files
                ) {
                    Map<String, String> map = ossUtil.uploadObject2OSS(file, Constants.BUCKET_HOUSE, Constants.FOLDER_HOUSE + "/" + request.getParameter("cid"));
                    log.info("房源图片上传返回信息-----{}", JSONObject.toJSONString(map));
                    if (map != null) {
                        ZfHousePicture housePicture = new ZfHousePicture();
                       housePicture.setType(type);
                        housePicture.setPath(map.get("path"));
                        housePicture.setUrl(map.get("url"));
                        housePicture.setProvinceCode(provCode);
                        housePicture.setCityCode(cityCode);
                        housePicture.setBasicId(Long.parseLong( request.getParameter("cid")));
                        // 保存图片信息
                         baseMapper.insert(housePicture);
                        Map<String,String> picMap = new HashMap<>();
                        picMap.put("id",String.valueOf(housePicture.getId()));
                        picMap.put("url",map.get("url"));
                        pictureList.add(picMap);
                    }
                }

                return Response.success(pictureList);
            }else {
                return Response.error("请上传图片");
            }

        } catch (Exception e) {
            return Response.error("上传失败");
        }
    }

    @Override
    public List<AdminHousePicDto> getPics(Long houseId, Long provCode, Long cityCode, int type) {
        return baseMapper.getPics(houseId,provCode,cityCode,type);
    }

    @Override
    public List<AdminHousePicDto> getPics(Long houseId, Long provCode, Long cityCode) {
        return baseMapper.getShikanPic(houseId, provCode, cityCode);
    }

    @Override
    public int delPic(Long houseId, Long provCode, Long cityCode, int type) {
        QueryWrapper<ZfHousePicture> housePictureQueryWrapper = new QueryWrapper<>();
        housePictureQueryWrapper.eq("type",type).eq("basic_id",houseId).eq("city_code",cityCode)
                .eq("province_code",provCode);
        return baseMapper.delete(housePictureQueryWrapper);
    }

    @Override
    public Response delHousepic(String ids,Long provCode, Long cityCode) {
        List<Long> idlist = Arrays.asList(ids.split(",")).parallelStream().map(a->Long.parseLong(a.trim())).collect(Collectors.toList());
        QueryWrapper<ZfHousePicture> wrapper = new QueryWrapper<>();
        wrapper.in("id",idlist).eq("city_code",cityCode)
                .eq("province_code",provCode);
        List<ZfHousePicture> dList = baseMapper.selectList(wrapper);
        //2、删除oss 图片
        for (ZfHousePicture pic : dList
        ) {
            //1、删除oss 中的图片资源
            ossUtil.deleteFile(Constants.BUCKET_HOUSE, pic.getPath());
        }
        int cn = baseMapper.delete(wrapper);
        if (cn > 0) {
            return Response.success("删除成功");
        }
        return Response.error("删除成功");
    }

    @Override
    public Response editPospic(Long id, Long provCode, Long cityCode,String pos) {
        try {
            baseMapper.editPos(id,provCode,cityCode,pos);
            return  Response.success("操作成功");
        }catch (Exception e){
            return  Response.success("操作失败");
        }

    }

    @Override
    @Transactional
    public void editShikan( String shikan, String huxing , Long provinceCode, Long cityCode) {
        // 实勘图编辑
        JSONArray tableData = JSONArray.parseArray(shikan);
        for (int i = 0; i < tableData.size(); i++) {
            JSONObject obj = (JSONObject)tableData.get(i);
            String id =  obj.getString("id");
            String pos = obj.getString("pos");
            this.editPospic(Long.parseLong(id), provinceCode, cityCode,pos);
        }
        // 户型图
        JSONObject ob = JSON.parseObject(huxing);
        if (ob!=null){
            // 先查询是否有更改
          int count =  this.hasHuxing(provinceCode,cityCode,ob.getString("path"));
          // 如果不存在可能已经变更或者不存在，则先进行删除在做添加
          if (count<=0){
              // 封面图每次选择之后先删除在增加
              this.delPic(Long.parseLong(ob.getString("houseId")),provinceCode,cityCode,3);
              ZfHousePicture picture = new ZfHousePicture();
              picture.setCityCode(cityCode);
              picture.setProvinceCode(provinceCode);
              picture.setUrl(ob.getString("url"));
              picture.setPath("noPath");
              picture.setType(3);
              picture.setBasicId(Long.parseLong(ob.getString("houseId")));
              baseMapper.insert(picture);
          }
        }
    }

    @Override
    public int hasHuxing(Long provinceCode, Long cityCode, String path) {
       QueryWrapper<ZfHousePicture> wrapper = new QueryWrapper<>();
       wrapper.lambda().eq(ZfHousePicture::getPath,path).eq(ZfHousePicture::getCityCode,cityCode).eq(ZfHousePicture::getProvinceCode,provinceCode);
       return  baseMapper.selectCount(wrapper);
    }

    public void calculateScore(Integer isElevator, BigDecimal floorScore, BigDecimal detail, Long basicId, Long cityCode, Long provCode) {
        // 电梯权重占30%， 楼层占70%(其中底层10%，低层20%,中楼层25%，高楼层30%，顶层15% )
        ZfHouseScore houseScore = new ZfHouseScore();
        BigDecimal score = new BigDecimal("0");
        // 推荐权重占30%
        if (isElevator == 0) {
            score = new BigDecimal("3");
        }
        BigDecimal floor = new BigDecimal("7").multiply(floorScore);
        houseScore.setDetailScore(score.add(floor));
        houseScore.setDetail(detail);
        houseScore.setBasicId(basicId);
        houseScore.setCityCode(cityCode);
        houseScore.setProvinceCode(provCode);
        // 更新房源分数
        scoreService.addOrUpdate(houseScore);

    }
}
